#include <stdio.h>
#include <stdlib.h>
#include <csp_spu.h>
#include <csp_debug.h>
#include "../../shared/mc_pi.h"



int global_pid; 

double mc_pi_calc(double iterations){
	double count=0, i, x, y, z;
	srand(csp_pid());
	for ( i=0; i<iterations; i++) {
		x = (double)rand()/RAND_MAX;
		y = (double)rand()/RAND_MAX;
		z = x*x+y*y;
		if (z<=1) count++;
	}

	return count;
}

int Run(){
	int i __attribute__ ((aligned(16)));
	double output_sum __attribute__ ((aligned(16)));
	int iterations __attribute__ ((aligned(16)));

	csp_channel master2slaves;
	csp_channel slaves2master;

	master2slaves = csp_create_channel(ONE2ANY_CHANNEL, MASTER2SLAVES, sizeof(int));
	slaves2master = csp_create_channel(ANY2ONE_CHANNEL, SLAVES2MASTER, sizeof(double));


	csp_channel_read(master2slaves, &iterations);

	output_sum = mc_pi_calc(iterations);

	printf("worker (pid=%i) did %i iterations, sum=%f, pi=%f.\n", 
		csp_pid(), iterations, output_sum, output_sum/iterations*4);

	csp_channel_write(slaves2master, &output_sum);

	return 0;
}
